import { AuthorAuditApi, updateAuthorStatus } from '@/api/audit/auth/author'
import {
  AuditStatus,
  Author,
  ContractStatus,
  UpdateAuthorStatusReq,
} from '@/api/audit/auth/model/authorModel'
import { useStore } from '@/store'
import { message } from 'ant-design-vue'
import { cloneDeep } from 'lodash-es'
import { computed, reactive } from 'vue'
import { AuditDialogState } from '../types'

const useAuditAuthor = (searchApi: () => Promise<void>) => {
  const store = useStore()
  const auditDialogState = reactive<AuditDialogState>({
    visiable: false,
    isDisable: false,
    authorDetail: {
      id: '',
      name: '',
      nick: '',
      phone: '',
      email: '',
      description: '',
      gender: 0,
      avatar: '',
      source: 0,
      sourceId: '',
      isRecommend: 0,
      sort: '',
      status: 0,
      outputs: 0,
      memo: '',
      contractStatus: 0,
      realName: '',
      identityType: 0,
      identityNo: '',
      birthDate: '',
      frontImg: '',
      backImg: '',
      favoriates: '',
      permanentAddress: '',
      isExclusive: 1,
      createTime: '',
      updateTime: '',
    },
  })

  const openAuditDialog = (authorInfo: Author) => {
    auditDialogState.visiable = true
    auditDialogState.isDisable = false
    auditDialogState.authorDetail = cloneDeep(authorInfo)
  }
  const openQueryAuditDialog = (authorInfo: Author) => {
    auditDialogState.visiable = true
    auditDialogState.isDisable = true
    auditDialogState.authorDetail = cloneDeep(authorInfo)
  }

  const onCloseAuditDialog = () => {
    auditDialogState.authorDetail.status = AuditStatus.ACCESS
  }

  const confirmAuditDialog = async () => {
    if (!auditDialogState.isDisable) {
      const reqData: UpdateAuthorStatusReq = {
        id: auditDialogState.authorDetail.id,
        status: auditDialogState.authorDetail.status,
        memo: auditDialogState.authorDetail.memo,
      }
      await updateAuthorStatus(reqData)
      message.success('审核成功！')
      await searchApi()
    }
    auditDialogState.visiable = false
  }
  const updateAuthorStatusLoading = computed(() =>
    store.getters['global/isOpLoading'](AuthorAuditApi.UPDATE_AUTHOR_STATUS)
  )

  const unContract = async (id: string) => {
    const reqData: UpdateAuthorStatusReq = {
      id,
      contractStatus: ContractStatus.UNCONTRACT,
    }
    await updateAuthorStatus(reqData)
    message.success('解约成功！')
    await searchApi()
  }
  const contract = async (id: string) => {
    const reqData: UpdateAuthorStatusReq = {
      id,
      contractStatus: ContractStatus.NORMAL,
    }
    await updateAuthorStatus(reqData)
    message.success('再签成功！')
    await searchApi()
  }

  return {
    auditDialogState,
    openAuditDialog,
    onCloseAuditDialog,
    confirmAuditDialog,
    openQueryAuditDialog,
    updateAuthorStatusLoading,
    unContract,
    contract,
  }
}

export default useAuditAuthor
